package fit.conceptmap.dao.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.transaction.Transactional;

import org.springframework.stereotype.Repository;

import fit.conceptmap.beans.UserBean;
import fit.conceptmap.dao.IUserDao;
import fit.conceptmap.entities.Role;
import fit.conceptmap.entities.User;
import fit.conceptmap.utils.Constants;
import fit.conceptmap.utils.PasswordUtils;

@Repository
public class UserDaoImpl implements IUserDao {
	@PersistenceContext
	private EntityManager em;
	
	@Override
	public List<User> getListUser() {
		TypedQuery<User> query = em.createQuery(
				"Select p From User p", User.class);
		return query.getResultList();
	}

	@Transactional
	public User getUserByUsername(String username) {
		String strQuery= "SELECT p From User p WHERE p.idUser = :idUser";
	    TypedQuery<User> query = em.createQuery(strQuery, User.class);
	    query.setParameter("idUser", username);
	    User user = query.getSingleResult();
		return user;
	}

	@Override
	@Transactional
	public boolean addNewUser(UserBean user) {
		boolean result = true;
		try {
			User entity = new User();
			entity.setIdUser(user.getIdUser());
			entity.setPassword(PasswordUtils.encodePassword(user.getPassword()));
			entity.setFullName(user.getFullName());
			SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
			Date date = formatter.parse(user.getDateBirth());
			entity.setDateBirth(date);
			Role role = em.find(Role.class, Constants.ROLE_USER);
			entity.setRoleBean(role);
			em.persist(entity);
		} catch (Exception e) {
			result = false;
		}
		return result;
	}

	@Override
	@Transactional
	public boolean updateUser(UserBean user) {
		boolean result = true;
		try {
			User entity = em.find(User.class, user.getIdUser());
			entity.setPassword(PasswordUtils.encodePassword(user.getPassword()));
			entity.setFullName(user.getFullName());
			SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
			Date date = formatter.parse(user.getDateBirth());
			entity.setDateBirth(date);
		} catch (Exception e) {
			result = false;
		}
		return result;
	}
}